package com.ecjtu.stadiumre_servations.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ecjtu.stadiumre_servations.entity.domain.GroupMember;
import com.ecjtu.stadiumre_servations.entity.domain.GroupRecord;
import com.ecjtu.stadiumre_servations.entity.domain.User;
import com.ecjtu.stadiumre_servations.mapper.GroupMemberMapper;
import com.ecjtu.stadiumre_servations.mapper.GroupRecordMapper;
import com.ecjtu.stadiumre_servations.mapper.UserMapper;
import com.ecjtu.stadiumre_servations.response.Result;
import com.ecjtu.stadiumre_servations.response.ResultCodeEnum;
import com.ecjtu.stadiumre_servations.service.GroupMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 拼团成员服务实现类
 * 负责处理拼团成员相关的业务逻辑，包括查询、添加、修改等操作
 */
@Service
public class GroupMemberServiceImpl extends ServiceImpl<GroupMemberMapper, GroupMember> implements GroupMemberService {

    @Autowired
    private GroupMemberMapper groupMemberMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private GroupRecordMapper groupRecordMapper;

    /**
     * 根据拼团记录ID查询所有成员
     * @param groupRecordId 拼团记录ID
     * @return 成员列表，按加入时间升序排列
     */
    @Override
    public Result selectByRecordId(String groupRecordId) {
        List<GroupMember> members = groupMemberMapper.selectList(
                new LambdaQueryWrapper<GroupMember>()
                        .eq(GroupMember::getGroupRecordId, groupRecordId)
                        .orderByAsc(GroupMember::getJoinTime)
        );
        return Result.build(members, ResultCodeEnum.SELECT_SUCCESS);
    }

    /**
     * 根据用户ID查询其参与的所有拼团
     * @param userId 用户ID
     * @return 拼团成员记录列表，按加入时间降序排列
     */
    @Override
    public Result selectByUserId(String userId) {
        List<GroupMember> members = groupMemberMapper.selectList(
                new LambdaQueryWrapper<GroupMember>()
                        .eq(GroupMember::getUserId, userId)
                        .orderByDesc(GroupMember::getJoinTime)
        );
        return Result.build(members, ResultCodeEnum.SELECT_SUCCESS);
    }

    /**
     * 检查用户是否已在拼团中
     * @param userId 用户ID
     * @param groupRecordId 拼团记录ID
     * @return true-已在拼团中，false-未在拼团中
     */
    @Override
    public Result isUserInGroup(String userId, String groupRecordId) {
        LambdaQueryWrapper<GroupMember> queryWrapper = Wrappers.<GroupMember>lambdaQuery()
                .eq(GroupMember::getUserId, userId);
        List<GroupMember> groupMemberList = groupMemberMapper.selectList(queryWrapper);
        boolean isInGroup = false;
        for (GroupMember g : groupMemberList) {
            if (g.getGroupRecordId().equals(groupRecordId)) {
                isInGroup = true;
                break;
            }
      }
        return Result.build(isInGroup, ResultCodeEnum.SELECT_SUCCESS);
    }

    /**
     * 查询用户在特定时间段参与的拼团
     * @param userId 用户ID
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return 符合条件的拼团成员记录列表
     */
    @Override
    public Result selectByUserAndTimeRange(String userId, String startTime, String endTime) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime start = LocalDateTime.parse(startTime, formatter);
        LocalDateTime end = LocalDateTime.parse(endTime, formatter);
        LambdaQueryWrapper<GroupMember> queryWrapper = Wrappers.<GroupMember>lambdaQuery()
                .eq(GroupMember::getUserId, userId)
                .ge(GroupMember::getJoinTime, start)
                .le(GroupMember::getJoinTime, end);

        List<GroupMember> members = groupMemberMapper.selectList(queryWrapper);
        return Result.build(members, ResultCodeEnum.SELECT_SUCCESS);
    }

    /**
     * 分页查询拼团成员
     * @param page 分页参数
     * @param recordId 拼团记录ID
     * @return 分页后的成员列表
     */
    @Override
    public Result selectPageByRecordId(Page<GroupMember> page, String recordId) {
        return Result.build(groupMemberMapper.selectPage(page, new LambdaQueryWrapper<GroupMember>().eq(GroupMember::getGroupRecordId, recordId)), ResultCodeEnum.SELECT_SUCCESS);
    }

    /**
     * 查询拼团的团长信息
     * @param recordId 拼团记录ID
     * @return 团长成员记录，如果不存在则返回null
     */
    @Override
    public Result selectLeaderByRecordId(String recordId) {
        LambdaQueryWrapper<GroupRecord> queryWrapper = Wrappers.<GroupRecord>lambdaQuery()
                .eq(GroupRecord::getRecordId, recordId);
        GroupRecord groupRecord = groupRecordMapper.selectOne(queryWrapper);
        User user = null;
        if (groupRecord != null) {
            user = userMapper.selectById(groupRecord.getLeaderUserId());
        }
        return Result.build(user, ResultCodeEnum.SELECT_SUCCESS);
    }

    /**
     * 查询用户作为团长的所有拼团
     * @param userId 用户ID
     * @return 拼团成员记录列表，按加入时间降序排列
     */
    @Override
    public Result selectLeaderGroupsByUserId(String userId) {
        List<GroupMember> members = groupMemberMapper.selectList(
                new LambdaQueryWrapper<GroupMember>()
                        .eq(GroupMember::getUserId, userId)
                        .eq(GroupMember::getIsLeader, true)
                        .orderByDesc(GroupMember::getJoinTime)
        );
        return Result.build(members, ResultCodeEnum.SELECT_SUCCESS);
    }

    /**
     * 删除拼团的所有成员
     * @param groupRecordId 拼团记录ID
     * @return true-删除成功，false-删除失败
     */
    @Override
    public Result deleteByRecordId(String groupRecordId) {
        boolean success = remove(
                new LambdaQueryWrapper<GroupMember>()
                        .eq(GroupMember::getGroupRecordId, groupRecordId)
        );
        return Result.build(success, ResultCodeEnum.DELETE_SUCCESS);
    }
    @Override
    public Result exitTheGroup(String groupRecordId, String userId) {
        if (groupRecordId == null || userId == null) {
            return Result.fail("该拼团信息不存在");
        }
        LambdaQueryWrapper<GroupMember> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(GroupMember::getGroupRecordId, groupRecordId)
                .eq(GroupMember::getUserId, userId);
        GroupMember groupMember = groupMemberMapper.selectOne(lambdaQueryWrapper);
        if (groupMember == null) {
            return Result.fail("您未参与该拼团");
        }
        if (groupMember.getIsLeader().equals("true")){
            return Result.fail("您是团长不可推出拼团");
        }
        GroupRecord groupRecord = groupRecordMapper.selectById(groupMember.getGroupRecordId());
        if (groupRecord.getRecordStatus().equals("已成团")) {
            return Result.fail("已成团,不可退出");
        }
        // 删除成员记录
        boolean success = remove(lambdaQueryWrapper);
        if (success) {
            // 更新拼团人数
            groupRecord.setCurrentSize(groupRecord.getCurrentSize() - 1);
            groupRecordMapper.updateById(groupRecord);
            return Result.ok("退出成功");
        }
        return Result.fail("退出失败");
    }
}